package com.party.core.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @Description: 图片处理工具
 * @Author: yangshoukun
 * @Date: 2018/5/11 17:25
 */
public class ImageUtils {
    /**
     * 将源文件图片更改为圆形头像
     * @param srcFile: 源图片路径
     * @param toFile: 修改后的圆形图片路径
     */
    public static File makeRoundedCornerImg(String srcFile, String toFile) throws IOException {
        File sFile = new File(srcFile);
        BufferedImage image = ImageIO.read(sFile);

        int w = image.getWidth();
        int h = image.getHeight();
        float x = 0;
        float y = 0;
        if (w >= h) {
            x = (w - h) / 2;
            w = h;
        } else {
            y = (h - w) / 2;
            h = w;
        }

        BufferedImage output = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = output.createGraphics();

        // 增加下面代码使得背景透明--使用透明背景时, 只能用png格式的图片
        output = g2.getDeviceConfiguration().createCompatibleImage(w, h, Transparency.TRANSLUCENT);
        g2.dispose();
        g2 = output.createGraphics();
        // 背景透明代码结束

        g2.setComposite(AlphaComposite.Src);

        // 设置抗锯齿
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(Color.WHITE);

        g2.fillRoundRect(0, 0, w, h, w, h);

        g2.setComposite(AlphaComposite.SrcAtop);

        g2.drawImage(image, -(int) x, -(int) y, null);
        g2.dispose();

        // 画外面的白圈
        int circleWidth = (int) (1.06 * w);
        int radius = circleWidth - w;
        BufferedImage bi3 = new BufferedImage(circleWidth, circleWidth, BufferedImage.TYPE_INT_RGB);
        Graphics2D g3 = bi3.createGraphics();

        // 增加下面代码使得背景透明
        bi3 = g3.getDeviceConfiguration().createCompatibleImage(circleWidth, circleWidth, Transparency.TRANSLUCENT);
        g3.dispose();
        g3 = bi3.createGraphics();
        // 背景透明代码结束

        // 设置抗锯齿
        g3.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g3.setColor(Color.WHITE);
        g3.fillRoundRect(0, 0, circleWidth, circleWidth, circleWidth, circleWidth);

        g3.drawImage(output, radius / 2, radius / 2, null);
        g3.dispose();

        String filetype = toFile.substring(toFile.lastIndexOf(".")+1);
        if (!"png".equals(filetype.toLowerCase())) {
            toFile = toFile.substring(0, toFile.lastIndexOf(".")) + ".png";
        }
        File file = new File(toFile);
        try {
            ImageIO.write(bi3, "png", file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return file;
    }

    /**
     * 删除文件
     * @param file
     * @return
     */
    public static boolean deleteFile(File file) {
        if (file.exists()) {
            return file.delete();
        }
        return true;
    }
}
